package swt.web;


import java.io.IOException;


import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swt.dao.CompDao;
import swt.dao.SaleDao;
import swt.dao.TrDao;


import swt.entity.Company;
import swt.entity.Tr;

public class AddServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			String task=request.getParameter("task");
			String method=request.getMethod();
			if(task==null||"".equals(task)){
				
			}else if("add".equals(task)){
				if("get".equalsIgnoreCase(method)){
					toadd(request,response);
				}else if("post".equalsIgnoreCase(method)){
					add(request,response);
				}
			}
			
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			
			String time=request.getParameter("time");
			String compname=new String(request.getParameter("compname").getBytes("iso8859-1"),"utf-8");
			
			String trname= new String(request.getParameter("trname").getBytes("iso8859-1"),"utf-8");
			int penum=Integer.parseInt(request.getParameter("penum"));
			String address=new String(request.getParameter("address").getBytes("iso8859-1"),"utf-8");
			float totalmoney=Float.parseFloat(request.getParameter("totalmoney"));
			
			float unitmoney=totalmoney/penum;
			
			SaleDao saledao=new SaleDao();
			CompDao compdao=new CompDao();
			TrDao trdao=new TrDao();
			
			Company comp=compdao.findByComName(compname);
			Tr tr=trdao.findByTrName(trname);
			
			if(comp==null){
				comp=new Company();
				
			
				comp.setCompname(compname);
				comp.setId(UUID.randomUUID().toString());
				compdao.save(comp.getCompname(),comp.getId());
			}
			if(tr==null){
				 tr=new Tr();
				tr.setTrname(trname);
				tr.setId(UUID.randomUUID().toString());
				trdao.save(tr.getTrname(),tr.getId());
			}	
			
			saledao.add(UUID.randomUUID().toString(), time,comp.getId(), tr.getId(), address, totalmoney, penum, unitmoney);
			
			request.getRequestDispatcher("main.jspx?task=all").forward(request,
					response);
	}
	private void toadd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			request.getRequestDispatcher("WEB-INF/view/add.jsp").forward(request, response);
		
	}
}
